<template>
  <div>
    <h2>ref</h2>
    <p>name: {{ name }} <input type="text" v-model="name" /></p>
    <p>age: {{ age }} <input type="text" v-model="age" /></p>
    <h2>reactive</h2>
    <p>name: {{ person.name }} <input type="text" v-model="person.name" /></p>
    <p>age: {{ person.age }} <input type="text" v-model="person.age" /></p>
    <p>
      女朋友: {{ person.girlFriend.name }}
      <input type="text" v-model="person.girlFriend.name" />
    </p>
  </div>
</template>

<script>
import { ref, watch, reactive } from "vue";

export default {
  setup() {
    let name = ref("Hydra");
    let age = ref(35);

    let person = reactive({
      name: "罗佰君",
      age: 24,
      girlFriend: { name: "小红" },
    });

    // 侦听一个数据
    // watch(name,(newVal,oldVal) => {
    //     console.log("newVal = ",newVal);
    //     console.log("oldVal = ",oldVal);
    // })

    // 侦听多个数据
    watch([name, age], ([newName, oldName], [newAge, oldAge]) => {
      console.log("newName = ", newName);
      console.log("oldName = ", oldName);

      console.log("newAge = ", newAge);
      console.log("oldAge = ", oldAge);
    });

    // 如果侦听reactive对象中的某一个属性，可以把第一个参数，变为一个getter函数，返回对象中的某个属性
    // 以下例子，表示监听person的name属性。注意：不能直接写成person.name
    // watch(() => person.name, (newVal, oldVal) => {
    //   console.log("newVal = ", newVal);
    //   console.log("oldVal = ", oldVal);
    // });

    // 深度监听和立即监听
    // 只监听到girlFriend对象，但是girlFrined只改了名字，也可以监听到
    watch(
      () => person.girlFriend,
      (newVal, oldVal) => {
        console.log("newVal = ", newVal);
        console.log("oldVal = ", oldVal);
      },
      { immediate: true, deep: true }
    );

    return { name, age, person };
  },
};
</script>

<style>
</style>